<template>
  <div class="orders-container">
    <div class="content-wrapper">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input 
          v-model="searchQuery" 
          placeholder="请输入商品名称进行搜索" 
          @input="handleSearch"
          clearable
          style="max-width: 400px; margin-right: 10px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>

      <!-- 商品列表 -->
      <div class="product-list">
        <div class="product-item" v-for="product in products" :key="product.id">
          <el-card class="product-card" shadow="hover">
            <div class="product-wrapper">
              <!-- 图片部分 -->
              <div class="product-image">
                <img :src="product.image || '@/img/img1.jpg'" :alt="product.name" />
              </div>

              <!-- 文字部分 -->
              <div class="product-details">
                <h4 class="product-name">{{ product.name }}</h4>
                <p class="product-description">{{ product.description }}</p>
                <div class="price-info">¥{{ product.price }}起</div>
                <el-button 
                  type="primary" 
                  class="add-cart-button" 
                  round 
                  @click="addToCart(product)"
                >
                  <el-icon><Plus /></el-icon>
                  <span>加入购物车</span>
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 购物车预览 -->
      <div class="cart-preview" v-show="cartItems.length > 0 && isCartVisible">
        <div class="cart-header">
          购物车
          <el-badge :value="cartItems.length" :hidden="cartItems.length === 0">
            <el-icon><ShoppingCart /></el-icon>
          </el-badge>
          <el-button type="danger" size="small" round class="clear-cart-button" @click="clearCart">
            清空购物车
          </el-button>
        </div>
        <div class="cart-items">
          <div class="cart-item" v-for="item in cartItems" :key="item.id">
            <span class="item-name">{{ item.name }}</span>
            <div class="item-control">
              <span class="item-price">¥{{ item.price }}</span>
              <el-input-number 
                v-model="item.quantity" 
                :min="0" 
                :max="99"
                size="small"
                @change="updateCart(item)"
              />
              <el-button type="danger" :icon="Delete" circle size="small" @click="removeItem(item.id)"></el-button>
            </div>
          </div>
        </div>
        <div class="cart-footer">
          <div class="total-price">总计：¥{{ totalPrice }}</div>
          <el-button type="success" round @click="submitOrder">去结算</el-button>
        </div>
      </div>
    </div>

    <!-- 购物车控制按钮 -->
    <div class="cart-toggle-button-container">
      <el-button type="primary" circle @click="toggleCartVisibility">
        <el-icon><ShoppingCart /></el-icon>
      </el-button>
    </div>

    <BottomNav />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Plus, ShoppingCart, Delete, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import BottomNav from '@/components/BottomNav.vue'
import { getAllGoods, getAllGoodsByCondition } from '@/api/cart.js'
import { submit } from '@/api/order.js'

const products = ref([])
const cartItems = ref([])
const searchQuery = ref('')
const isCartVisible = ref(true) // 控制购物车的显示与隐藏

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0).toFixed(2)
})
const fetchProducts = async (name = '') => {
  try {
    const response = await getAllGoodsByCondition(name)
    if (response.code === 1) {
      products.value = response.data
    }
  } catch (error) {
    console.error('获取商品列表失败：', error)
  }
}
const handleSearch = () => {
  fetchProducts(searchQuery.value)
}

const addToCart = (product) => {
  const existingItem = cartItems.value.find(item => item.id === product.id)
  if (existingItem) {
    existingItem.quantity++
  } else {
    cartItems.value.push({
      ...product,
      quantity: 1
    })
  }
}

const updateCart = (item) => {
  if (item.quantity === 0) {
    cartItems.value = cartItems.value.filter(cartItem => cartItem.id !== item.id)
  }
}

const clearCart = () => {
  cartItems.value = []
  ElMessage.success('购物车已清空')
}

const removeItem = (id) => {
  cartItems.value = cartItems.value.filter(item => item.id !== id)
  ElMessage.success('商品已从购物车移除')
}
const submitOrder = async () => {
  // 封装data
  const data = {
    information: cartItems.value
      .map(item => `${item.name} x${item.quantity}`)
      .join(','),
    expend: parseFloat(totalPrice.value),
    items: cartItems.value.map(item => ({
      goodId: item.id,
      goodName: item.name,
      quantity: item.quantity,
      price: item.price
    }))
  }

  try {
    // 调用API
    const response = await submit(data)
    console.log(response.data)
    // 根据后端返回数据判断提示信息
    if (response.code === 1) {
      // 确保 ElMessage.success 接收到的是字符串
      ElMessage.success(String(response.data)) // 将后端返回的成功消息转换为字符串
      cartItems.value = [] // 清空购物车
    } else {
      ElMessage.error(response.msg || '订单提交失败') // 显示后端返回的失败消息或默认失败信息
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error('网络错误，请重试')
  }
}
const toggleCartVisibility = () => {
  isCartVisible.value = !isCartVisible.value // 切换购物车的显示状态
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.orders-container {
  padding-bottom: 120px;
}

.content-wrapper {
  padding: 16px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-bar .el-input {
  flex: 1;
  max-width: 400px;
  transition: all 0.3s ease;
}

.search-bar .el-input:hover {
  box-shadow: 0 0 8px rgba(92, 107, 192, 0.2);
}

.search-bar .el-button {
  margin-left: 10px;
  background-color: #5c6bc0;
  border-color: #5c6bc0;
  color: white;
  font-weight: bold;
  transition: background-color 0.3s ease;
}

.search-bar .el-button:hover {
  background-color: #3949ab;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.product-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  padding: 12px;
}

.product-wrapper {
  display: flex;
  align-items: center; /* 图片和文字水平对齐 */
  gap: 16px; /* 图片与文字之间留出间距 */
}

/* 左侧图片区域 */
.product-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
  background-color: #f0f0f0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 右侧信息区域 */
.product-details {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex-grow: 1;
  min-width: 0; /* 防止文字溢出 */
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0 0 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-description {
  font-size: 14px;
  color: #777;
  margin: 4px 0 8px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price-info {
  font-size: 16px;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 8px;
}

.add-cart-button {
  align-self: flex-end; /* 靠右对齐 */
  font-size: 14px;
  padding: 10px 20px;
  background-color: #5c6bc0;
  border-color: #5c6bc0;
  color: white;
  transition: all 0.3s ease;
}

.add-cart-button:hover {
  background-color: #3949ab;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(92, 107, 192, 0.3);
}

.el-icon {
  right: 0;
  bottom: 0;
  margin-right: 4px;
}

/* 购物车样式美化 */
.cart-preview {
  position: fixed;
  bottom: 60px;
  left: 0;
  right: 0;
  background: #fff;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.15);
  padding: 16px;
  border-radius: 16px 16px 0 0;
  z-index: 100;
}

.cart-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
  justify-content: space-between;
}

.cart-header .el-icon {
  margin-right: 8px;
  font-size: 22px;
  color: #ff6b6b;
}

.clear-cart-button {
  margin-left: auto;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px dashed #eee;
}

.item-control {
  display: flex;
  align-items: center;
  gap: 10px;
}

.item-control .el-input-number {
  width: 100px;
}

.item-control .el-button.is-circle {
  padding: 6px;
}

.cart-items {
  max-height: 200px;
  overflow-y: auto;
  padding-right: 8px;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-name {
  font-size: 15px;
  color: #555;
  flex-grow: 1;
  margin-right: 10px;
}

.item-price {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 15px;
}

.item-control .el-input-number__decrease,
.item-control .el-input-number__increase {
  background-color: #f0f0f0;
  color: #333;
}

.item-control .el-input-number__decrease:hover,
.item-control .el-input-number__increase:hover {
  background-color: #e0e0e0;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #eee;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
}

.cart-footer .el-button {
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 20px;
}

.el-message {
  min-width: 350px !important;
  font-size: 16px !important;
}

.el-message__content {
  font-size: 16px !important;
}

/* 购物车控制按钮样式 */
.cart-toggle-button-container {
  position: fixed;
  bottom: 20px; /* 距离底部的距离 */
  left: 50%; /* 水平居中 */
  transform: translateX(-50%); /* 精确居中 */
  z-index: 100;
}

.cart-toggle-button-container .el-button {
  padding: 10px;
  font-size: 20px;
  background-color: #5c6bc0;
  border-color: #5c6bc0;
  color: white;
  transition: all 0.3s ease;
}

.cart-toggle-button-container .el-button:hover {
  background-color: #3949ab;
}
</style>